﻿#region Licence
// <copyright file="SampleModule/AppelsAccueilViewModel.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>26/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.Linq;
using Database.POCO;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using Helpers.Contracts;
using Helpers.Messages;
using Interfaces.Enums;
using SampleModule.Class;
using SampleModule.ViewModels;

#endregion

namespace SampleModule.MefExport.AccueilContract
{
    [ExportAccueil(TypeModulesEnum.Appels, "09a02d29-d7cb-4efd-a144-4165e7024c04", "AppelsLocalized")]
    public class AccueilContractViewModel : AccueilContractBase
    {
        #region properties

        private List<AppelWithPersonnes> _appels;
        public List<AppelWithPersonnes> Appels
        {
            get { return _appels; }
            set
            {
                _appels = value;
                RaisePropertyChanged(() => Appels);
            }
        }

        public RelayCommand CreateAppelCommand { get; set; }
        public RelayCommand OpenAppelsCommand { get; set; }
        #endregion

        #region cstor

        public AccueilContractViewModel()
        {
            CreateAppelCommand = new RelayCommand(CreateAppel, CanCreateAppel);
            OpenAppelsCommand = new RelayCommand(OpenAppels, CanOpenAppels);
        }

        #endregion

        #region relaycommand

        private bool CanOpenAppels()
        {
            return Appels.Count > 0;
        }

        private void OpenAppels()
        {
            Services.NavigationService.NavigateTo<AccueilAppelsViewModel>(base.SenderViewModel, new object[] {}, true);
            Messenger.Default.Send<CurrentModuleMessage>(new CurrentModuleMessage(){ CurrentModule = TypeModulesEnum.Appels});
        }

        private bool CanCreateAppel()
        {
            ValueRightsEnum rights;
            if (Services.AccessControlService.IsAuthorizedFunction(Services.RightsService.GetIdentifiantRight((int)RightsEnum.Appel, TypeModulesEnum.Appels), out rights))
            {
                return rights.HasFlag(ValueRightsEnum.Modification);
            }
            return false;
        }

        private void CreateAppel()
        {
            Services.NavigationService.NavigateTo<CreateOrUpdateAppelViewModel>(base.SenderViewModel, new object[] { new SampleAppel() }, true);
            Messenger.Default.Send<CurrentModuleMessage>(new CurrentModuleMessage() { CurrentModule = TypeModulesEnum.Appels });
        }

        #endregion

        /// <summary>
        /// Permet de rafaichir les données exposées dans le module
        /// </summary>
        public override void Refresh(ViewModelBase sender)
        {
            base.RegisterSender(sender);

            var appelsFound = new List<SampleAppel>();

            var id = Services.AccessControlService.CurrentUser.ID;
            var appelsUser = Services.DatabaseService.Service.Where<SampleAppelUtilisateurs>(a => a.Destinataire.ID == id && a.IsView == false);
            if (Services.DatabaseService.Service.Any<SampleAppel>())
            {
                var appels =
                    Services.DatabaseService.Service.Where<SampleAppel>(
                        a =>
                            a.SysDateCreation.Month == DateTime.Now.Month &&
                            a.SysDateCreation.Year == DateTime.Now.Year).ToList();

                foreach (var utilisateur in appelsUser)
                {
                    appelsFound.AddRange(appels.Where(a => a.ID == utilisateur.Appel.ID));
                }
            }

            Appels = CreateCollectionAppelWithPersonnes(appelsFound);
        }

        #region private
        
        private List<AppelWithPersonnes> CreateCollectionAppelWithPersonnes(IEnumerable<SampleAppel> appels)
        {
            var list = new List<AppelWithPersonnes>();
            foreach (var appel in appels.OrderByDescending(a => a.SysDateCreation))
            {
                var appelWithPerson = new AppelWithPersonnes {Appel = appel, Personnes = new List<SysUtilisateur>()};

                SampleAppel appel1 = appel;
                var personnes = Services.DatabaseService.Service.Where<SampleAppelUtilisateurs>(a => a.Appel.ID == appel1.ID);
                foreach (var personne in personnes)
                {
                    appelWithPerson.Personnes.Add(personne.Destinataire);
                }

                list.Add(appelWithPerson);
            }
            return list;
        }
        #endregion
    }
}
